#include "voc.h"
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include "cmsis_os2.h"
#include "app_init.h"
#include "soc_osal.h"

#include "common_def.h"
#include "pinctrl.h"
#include "uart.h"

#include "watchdog.h"
#include "osal_debug.h"

#include "gpio.h"

#include "../mydevice/mydevice.h"

static uint8_t voc_uart_rx_buff[UART_TRANSFER_SIZE] = { 0 };
static uart_buffer_config_t voc_buffer_config = {
    .rx_buffer = voc_uart_rx_buff,
    .rx_buffer_size = UART_TRANSFER_SIZE
};

// 解析VOC空气质量
uint16_t voc_value;
// 解析甲醛
uint16_t formaldehyde;
// 解析eCO2
uint16_t eco2;
float temperature;
float humidity;
static void voc_gpio_init(uint16_t uart_bus,uint16_t uart_tx,uint16_t uart_rx )
{
    if(uart_bus==1||uart_bus==0){
        uapi_pin_set_mode(uart_tx, PIN_MODE_1);
        uapi_pin_set_mode(uart_rx, PIN_MODE_1);
    }
    else if(uart_bus==2){
        uapi_pin_set_mode(uart_tx, PIN_MODE_2);
        uapi_pin_set_mode(uart_rx, PIN_MODE_2);
    }
}
// 初始化 UART 配置
static void voc_init_config(uint16_t uart_bus,uint16_t uart_tx,uint16_t uart_rx,uart_buffer_config_t* buff_config)
{
    // 定义一个 uart_attr_t 类型的结构体变量 attr，用于存储 UART 的属性
    uart_attr_t attr = {
        .baud_rate = 9600, .data_bits = UART_DATA_BITS, .stop_bits = UART_STOP_BITS, .parity = UART_PARITY_BIT};

    uart_pin_config_t pin_config = {.tx_pin = uart_tx, .rx_pin = uart_rx, .cts_pin = PIN_NONE, .rts_pin = PIN_NONE};
    uapi_uart_deinit(uart_bus);
    int ret = uapi_uart_init(uart_bus, &pin_config, &attr, NULL, buff_config);
    if (ret != 0) {
        printf("uart init failed ret = %02x\n", ret);
    }
}
static void process_voc_data(uint8_t *data, uint16_t length) {
    // 检查数据长度是否足够
    if (length < 12) {
        osal_printk("Data length is insufficient.\r\n");
        return;
    }

    // 检查帧头是否正确
    if (data[0] != 0x2C) {
        osal_printk("Invalid frame head.\r\n");
        return;
    }

    // 计算校验和
    uint8_t checksum = 0;
    for (int i = 0; i < 11; i++) {
        checksum += data[i];
    }
    checksum = ~checksum + 1; // 取反加1
    
    // 验证校验和
    if (checksum != data[11]) {
        osal_printk("Checksum verification failed.\r\n");
        return;
    }
    uint8_t df1 = data[1];
    // 解析VOC空气质量
    voc_value = (uint16_t)(df1 << 8) | data[2];

    df1 = data[3];
    // 解析甲醛
    formaldehyde = (uint16_t)(df1 << 8)|data[4];
    
    // 解析eCO2
    df1 = data[5];
    eco2 = (uint16_t)(df1 << 8)| data[6];
    
    // 解析温度 (0.1°C)
    df1 = data[7];
    uint16_t temp_raw = (uint16_t)(df1 << 8)|data[8];
    temperature = temp_raw / 10.0f;
    
    // 解析湿度 (0.1%RH)
    df1 = data[9];
    uint16_t hum_raw = (uint16_t)(df1 << 8)| data[10];
    humidity = hum_raw / 10.0f;

    // // 将数据保存到结构体
    // SensorData* sensorData=
    // snprintf(sensorData.temperature, sizeof(sensorData.temperature), "%.1f", temperature);
    // snprintf(sensorData.humidity, sizeof(sensorData.humidity), "%.1f", humidity);
    // snprintf(sensorData.co2, sizeof(sensorData.co2), "%d", eco2);

    // 输出所有解析结果
    // osal_printk("VOC: %d ug/m3\r\n", voc_value);
    // osal_printk("Formaldehyde: %d ug/m3\r\n", formaldehyde);
    // osal_printk("eCO2: %d PPM\r\n", eco2);
    // // 修改后的打印语句
    // osal_printk("Temperature: %d.%d °C\r\n", (int)temperature, (int)((temperature*10.0 - (int)temperature*10)));
    // osal_printk("Humidity: %d.%d %%RH\r\n", (int)humidity, (int)((humidity*10.0 - (int)humidity*10)));
}

void get_voc_data() {
    char frame[50] = {0}; // 帧缓冲区，足够大以存储所有数据

    // 定义帧头和帧尾
    unsigned char frame_head[] = {0xFE, 0xA5, 0x00, 0x00, 0xA5};

    // 将帧头添加到帧缓冲区
    memcpy(frame, frame_head, sizeof(frame_head));

    size_t frame_length = sizeof(frame_head);

    // 发送帧数据
    uapi_uart_write(CONFIG_VOC_BUS, (unsigned char *)frame, frame_length, 0);

    for (int i = 0; i < 5; i++) {
        if (uapi_uart_read(CONFIG_VOC_BUS, voc_uart_rx_buff, UART_TRANSFER_SIZE, 0) > 0) {
            // osal_printk("uart%d poll mode receive succ!, g_app_uart_rx_buff = %s\r\n", CONFIG_VOC_BUS,
            //             voc_uart_rx_buff);
            // 处理接收到的数据
            process_voc_data(voc_uart_rx_buff, UART_TRANSFER_SIZE);

            break;
        }
        osal_msleep(10);
    }
}

void voc_init() {
    // 初始化UART GPIO引脚
    voc_gpio_init(CONFIG_VOC_BUS, CONFIG_VOC_TXD_PIN, CONFIG_VOC_RXD_PIN);
    // uart_gpio_init(CONFIG_LORA_BUS, CONFIG_LORA_TXD_PIN, CONFIG_LORA_RXD_PIN);
    // 初始化UART配置
    voc_init_config(CONFIG_VOC_BUS, CONFIG_VOC_TXD_PIN, CONFIG_VOC_RXD_PIN, &voc_buffer_config);
    // 注销UART接收回调函数pm2_5_buffer_config
    uapi_uart_unregister_rx_callback(CONFIG_VOC_BUS);
}

uint16_t get_voc_value() {
    return voc_value;
}

uint16_t get_formaldehyde_value() {
    return formaldehyde;
}

uint16_t get_eco2_value() {
    return eco2;
}

float get_temperature_value() {
    return temperature;
}

float get_humidity_value() {
    return humidity;
}